<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use OpenTracing\Tracer;
use const OpenTracing\Formats\TEXT_MAP;

/**
 * Class OpenTracingMiddleware
 * @package W7\Sdk\Shop\Package\OpenTracing\Middleware
 */
class OpenTracingMiddleware
{
    /**
     * @var Tracer
     */
    private $tracer;
    /**
     * @var \OpenTracing\Span
     */
    private $span;

    public function __construct()
    {
    }

    /**
     * @throws \Throwable
     */
    public function handle(Request $request, \Closure $next)
    {
        $this->tracer = app(Tracer::class);

        $spanContext = $this->tracer->extract(TEXT_MAP, getallheaders());

        $scope = $this->tracer->startActiveSpan(
            $request->url(), [
            'child_of' => $spanContext
        ]);
        $span = $scope->getSpan();
        $span->setTag(\OpenTracing\Tags\HTTP_URL, $request->url());
        $span->setTag(\OpenTracing\Tags\HTTP_METHOD, $request->method());


        try {
            /** @var Response $response */
            $response = $next($request);
            
            $span->setTag(\OpenTracing\Tags\HTTP_STATUS_CODE, $response->getStatusCode());

            return $response;
        } catch (\Throwable $e) {
            $span->log([$e->getMessage()]);
            throw $e;
        } finally {
            $span->finish();
            $this->tracer->flush();
        }
    }
}
